from flask import request, json, g
from utils.common import response_error, response_other, response_get
from utils.token import check_token
from databases import db_configs, HandleDb
from . import common_func
import time

# 不检查的路径
url_break_tokens = [
    'static'
]


# 如果能走到路由处理函数则表示验证成功!
def check_user_is_admin():
    is_check = False
    url = request.url
    for url_ in url_break_tokens:
        if url.find(url_) != -1:
            break
    else:
        is_check = True

    # 每次请求初始化数据库
    g.db_1: HandleDb = HandleDb(**db_configs.LOCALHOST_DB_FLASK_DEMO_CONFIG)
    g.db_2: HandleDb = HandleDb(**db_configs.LOCALHOST_DB_GALLERY_CONFIG)

    if is_check:
        token = request.headers.get('token')
        if not token:
            return response_error(401, "not token!")
        result = check_token(token)
        if not result:
            return response_error(401, "token error!")
        username = result.get('username')
        exp = result.get('exp')
        users = g.db_1.find('user', 'authority', f'name = "{username}"')
        if not len(users):
            return response_error(401, "token验证不通过")
        if users[0]['authority'] != '管理员':
            return response_error(401, "此用户不是管理员")
        if exp < time.time():
            return response_error(401, "token已经过期!")
        # print("验证通过!", 'admin_before_request')
    else:
        pass
        # print("跳过验证!", 'admin_before_request')


def after_request_func(response):
    # 当请求响应以后,并且没有错误,才会走这里
    # 释放数据库资源
    if g.get('db_1'):
        g.db_1.close()
    if g.get('db_2'):
        g.db_2.close()
    return response


def index():
    return response_other(200, "验证通过!")


# 任务
def caiji_task():
    # 添加
    # 删除
    # 修改
    pass


# 首页频道
def index_channel():
    method = request.method
    try:
        if method == 'GET':
            id = request.args.get('id', None)
            if not id is None:
                result = g.db_1.find('`a_home`', '*', f'id = {id}')
                if result != 'error':
                    return response_get(200, result)
            else:
                result = g.db_1.find('a_home')
                if result != 'error':
                    return response_get(200, result)
        elif method == 'POST':
            json_str = request.get_data()
            body_data = json.loads(json_str)
            result = common_func.check_body_data_format(body_data)
            if not result:
                return response_error()
            result = g.db_1.add('a_home', result)
            if result != 'error':
                return response_other()
            return response_error()

        elif method == 'PUT':
            json_str = request.get_data()
            body_data = json.loads(json_str)
            if body_data.get('id'):
                id = body_data.pop('id')
                result = common_func.check_body_data_format(body_data)
                if not result:
                    result = g.db_1.update('a_home', result, f'id = {id}')
                    if result != 'error':
                        return response_other()
            return response_error()

        elif method == 'DELETE':
            json_str = request.get_data()
            body_data = json.loads(json_str)
            id = body_data.get('id')
            if not id is None:
                result = g.db_1.delete('a_home', f'id = {id}')
                if result != 'error':
                    return response_other()

        return response_error(500)
    except Exception as e:
        print(e)
        return response_error(500)


# 小说
def book():
    method = request.method
    try:
        if method == 'GET':
            id = request.args.get('id')
            # 获取总数量
            result = g.db_1.find('book', 'count(id)')
            if result != 'error':
                book_count = result[0]['count(id)']
            else:
                return response_error(500)
            # 获取单个
            if id:
                result = g.db_1.sql(f'select book.*,category.name as category_name from book inner join category on '
                                    f'book.category_id = category.id and book.id = {id}')
                if result != 'error':
                    return response_get(200, {"data": result, "count": book_count})
            # 分页
            else:
                page = request.args.get('page', 1)
                count = request.args.get('count', 10)
                try:
                    page = int(page)
                    count = int(count)
                except:
                    return response_error(400)

                title = request.args.get('q_title', '')
                cate_name = request.args.get("q_cate_name", '')
                book_author = request.args.get('q_author', '')

                # 获取总数量
                result = g.db_1.sql(
                    f'select count(id) from book where category_id in (select category.id from category '
                    f'where `name` like "%{cate_name}%") and book_title like "%{title}%" an'
                    f'd book_author like "%{book_author}%"')
                if result != 'error':
                    book_count = result[0]['count(id)']
                else:
                    return response_error(500)
                # 子查询 + 模糊查询 + 分页
                # limit start,end
                result = g.db_1.sql(
                    f'select book.*,category.name as category_name from book inner join category where category_id in (select category.id from category '
                    f'where `name` like "%{cate_name}%") and book_title like "%{title}%" an'
                    f'd book_author like "%{book_author}%" limit {(page - 1) * count},{count} ')
                if result != 'error':
                    return response_get(200, {"data": result, "count": book_count})

        return response_error(500)
    except Exception as e:
        print(e)
        return response_error(500)


# 获取小说详情
def book_detail(id):
    if id:
        # 查找该id对应的分类
        result = g.db_1.find('book', 'category_id', f'id = {id}')
        if result == 'error':
            return response_error()
        if result == 'ok':
            return response_get()

        category_id = result[0]['category_id']
        result = g.db_1.find('category', '*', f'id = {category_id}')

        if result == 'error':
            return response_error()
        if result == 'ok':
            return response_get()

        table_name_content = result[0]['table_name_content']
        table_name_directory = result[0]['table_name_directory']

        result1 = g.db_1.sql(
            f"select `{table_name_directory}`.book_id,count(`{table_name_directory}`.id) as direction_count from `{table_name_directory}` where book_id = {id} GROUP BY `{table_name_directory}`.book_id")
        result2 = g.db_1.sql(
            f"select `{table_name_directory}`.book_id,count(`{table_name_content}`.id) as content_count from `{table_name_content}` INNER JOIN `{table_name_directory}` on directory_id = `{table_name_directory}`.id  where book_id = {id} GROUP BY `{table_name_directory}`.book_id")
        if isinstance(result1, list) and isinstance(result2, list):
            data = result1[0]
            data.update(result2[0])
            return response_get(200, data=data)

        return response_get()


# 图片
def img(id):
    method = request.method
    if method == 'GET':
        if id:
            g.db_1.find('')
        else:
            pass

    elif method == 'POST':
        if id:
            pass

    elif method == 'PUT':
        if id:
            pass

    elif method == 'DELETE':
        if id:
            pass
    return response_error()
